#include <bits/stdc++.h>
using namespace std;
#define int long long

const int N = 51;
int T;
int n, m;
int ret = 0;

int grap[N][N];
bool sea_grap[N][N];
bool land_grap[N][N];

int sx[8] = {0, 0, -1, 1, 1, 1, -1, -1};
int sy[8] = {-1, 1, 0, 0, -1, 1, -1, 1};
int lx[4] = {0, 0, -1, 1};
int ly[4] = {-1, 1, 0, 0};

bool chick(int x, int y)
{
	return (x >= 0 && x < n && y >= 0 && y < m);
}

void land_dfs(int i, int j)
{
	land_grap[i][j] = true;
	for (int k = 0; k < 4; k++)
	{
		int x = i + lx[k], y = j + ly[k];
		if (chick(x, y) && grap[x][y] == 1 && !land_grap[x][y])
			land_dfs(x, y);
	}
}

void sea_dfs(int i, int j)
{
	sea_grap[i][j] = true;
	for (int k = 0; k < 8; k++)
	{
		int x = i + sx[k], y = j + sy[k];
		if (chick(x, y) && grap[x][y] == 0 && !sea_grap[x][y])
			sea_dfs(x, y);
			
		if (chick(x, y) && grap[x][y] == 1 && !land_grap[x][y])
		{
			ret++;
			land_dfs(x, y);
		}
	}
}
void slove()
{
	cin >> n >> m;
	ret = 0;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			sea_grap[i][j] = land_grap[i][j] = false;
	
	for (int i = 0; i < n; i++)
	{
		string s;
		cin >> s;
		for (int j = 0; j < m; j++)	
			grap[i][j] = s[j] - '0';
	}
	
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
		{
			if ((i == 0 || i == n - 1 || j == 0 || j == m - 1) && grap[i][j] == 0)
				sea_dfs(i, j);
		}
	cout << ret << endl;
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	
	cin >> T;
	while (T--)
		slove();
	return 0;
}